package com.wzl.thread.controller;

import com.wzl.thread.service.TcThreadLocalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * ThreadLocal使用
 *
 * @author weizhongli
 * @since 2022-09-01 21:04
 *
 * https://mp.weixin.qq.com/s/KvRWJFcec3vqMxn8kEmAxA
 *
 */
@Controller
public class TcThreadLocalController {

    //https://blog.csdn.net/qq_35190492/article/details/116431270?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522166203809016781647570911%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=166203809016781647570911&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-4-116431270-null-null.142^v44^new_blog_pos_by_title&utm_term=threadLocal%E4%BD%BF%E7%94%A8&spm=1018.2226.3001.4187

    @Autowired
    private TcThreadLocalService tcThreadLocalService;

    private static ThreadLocal<String> localInt = new ThreadLocal<String>();


    //ThreadLocal提供了一个withInitial()方法统一初始化所有线程的ThreadLocal的值：
    private static ThreadLocal<Integer> localInt1 = ThreadLocal.withInitial(() -> 6);


    public static String setAndGet() {
        localInt.set("哈哈哈");
        String s = localInt.get();
        return s;
    }

    static void print() {
        //打印当前线程中本地内存中本地变量的值
        System.out.println("线程" + Thread.currentThread().getName() + "----" + " :" + localInt.get());
        //清除本地内存中的本地变量
        localInt.remove();
    }

    public static void main(String[] args) throws InterruptedException {
//        String s = setAndGet();
//        //清除本地内存中的本地变量
//        localInt.remove();
//        System.out.println(s);

        new Thread(new Runnable() {
            public void run() {
                TcThreadLocalController.localInt.set("local_A");
                print();
                //打印本地变量
                System.out.println("调用remove方法后:  " + localInt.get());

            }
        }, "A").start();

        Thread.sleep(1000);

        new Thread(new Runnable() {
            public void run() {
                TcThreadLocalController.localInt.set("local_B");
                print();
                System.out.println("after remove : " + localInt.get());

            }
        }, "B").start();

    }


}
